import { sign } from 'jsonwebtoken'
import mongoose from 'mongoose'
import { NotificationTemplate } from '../models/NotificationTemplate'
import { Room } from '../models/Room'
import { User } from '../models/User'

// 创建测试用户
export const createTestUser = async (role: 'user' | 'admin' = 'user') => {
  const user = await User.create({
    username: `test-${role}`,
    password: 'password',
    nickname: role === 'admin' ? 'Admin' : 'User',
    role,
  })

  const token = sign({ userId: user._id }, process.env.JWT_SECRET!)
  return { user, token }
}

// 创建测试房间
export const createTestRoom = async (hostId: string) => {
  return Room.create({
    title: 'Test Room',
    description: 'Test Description',
    host: hostId,
    status: 'offline',
    category: 'game',
  })
}

// 创建测试通知模板
export const createTestTemplate = async () => {
  return NotificationTemplate.create({
    code: 'test-template',
    type: 'system',
    title: 'Test Title ${name}',
    content: 'Test Content ${message}',
    variables: ['name', 'message'],
  })
}

// 清理数据库
export const clearDatabase = async () => {
  const collections = await mongoose.connection.db.collections()
  for (const collection of collections) {
    await collection.deleteMany({})
  }
}

// 生成测试ID
export const generateTestId = () => new mongoose.Types.ObjectId().toString()

// 等待指定时间
export const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))
